// 导入db模块
const db = require("../common/db");
// 导入加密模块
const aes = require("../common/aes/indes");
const { v4: uuidv4 } = require("uuid");

// 在注册用户时生成 UUID
let id = uuidv4();

class User {
  // 注册
  register(account, password) {
    return new Promise((resolve, reject) => {
      // 执行查询用户sql语句
      //  db.query(`select 字段  from  数据表   where 字段=值`)
      db.query(`select 账号  from  pre_user   where 账号='${account}'`).then(
        (rows) => {
          if (rows.length == 0) {
            // 未注册
            // 对密码进行加密
            let pwd = aes.aesEncrypt(password);
            // 记录用户注册的时间
            let date = new Date();
            let time = date.getTime(); //时间戳（以后可以根据时间戳获取年月日时分秒）
            // 获取年、月、日、小时、分钟和秒
            let year = date.getFullYear();
            let month = date.getMonth() + 1; // 月份从0开始，所以要加1
            let day = date.getDate();
            let hours = date.getHours();
            let minutes = date.getMinutes();
            let seconds = date.getSeconds();
            // 格式化输出
            let formattedDate = `${year}-${month < 10 ? "0" + month : month}-${
              day < 10 ? "0" + day : day
            } ${hours < 10 ? "0" + hours : hours}:${
              minutes < 10 ? "0" + minutes : minutes
            }:${seconds < 10 ? "0" + seconds : seconds}`;
            // let num = Math.floor(Math.random() * 5 + 1);
            // let imgUrl = `/static/images/${num}.jpg`;
            // 执行插入数据的sql语句
            db.query(
              `insert into pre_user(ID号,注册时间,账号,密码) values('${id}','${formattedDate}','${account}','${pwd}')`
            ).then(
              (content) => {
                resolve({
                  code: 200,
                  msg: "恭喜您，注册账号成功",
                  status: content.changedRows == 0 ? "正常" : "异常",
                });
              },
              (err) => {
                reject({
                  code: -1,
                  msg: "注册失败",
                  err,
                });
              }
            );
          } else {
            // 已注册
            resolve({
              code: 1,
              msg: `该账号已存在,${account}`,
            });
          }
        },
        (err) => {
          //  出现异常
          reject({
            code: 500,
            msg: "后台出现异常",
            err,
          });
        }
      );
    });
  }

  // 登录
  login(account, password) {
    return new Promise((resolve, reject) => {
      db.query(
        `select  账号,密码 from  pre_user  where 账号 = '${account}'`
      ).then(
        (rows) => {
          if (rows.length == 0) {
            resolve({
              code: 404,
              msg: `该账号不存在，${account}`,
            });
          } else {
            // 解构赋值
            let [user] = rows;
            // console.log("检查:",user);
            // console.log(user.密码)
            if (user.密码) {
              // 通过布尔值 判断密码是否一致
              // let isLogin = aes.aesDecrypt(明文（用户提交的参数）, 加密的（数据表中的字段）)
              let isLogin = aes.aesDecrypt(password, user.密码);
              //   console.log({ isLogin });
              if (isLogin) {
                // 给前端提示
                resolve({
                  code: 200,
                  msg: `${account},登录成功`,
                });
              } else {
                // 提示
                resolve({
                  code: -1,
                  msg: `账号或密码错误`,
                });
              }
            }
          }
        },
        (err) => {
          reject({
            code: 500,
            msg: "后台发生错误",
            err,
          });
        }
      );
    });
  }

  // 登录(管理员)
  signin(account, password, role) {
    return new Promise((resolve, reject) => {
      db.query(
        `select  *  from  pre_user  where 账号 = '${account}' and 角色='${role}'`
      ).then(
        (rows) => {
          if (rows.length == 0) {
            resolve({
              code: 404,
              msg: `该账号不存在，${account}`,
            });
          } else {
            // 解构赋值
            let [user] = rows;
            // console.log("检查:",user);
            if (user.密码) {
              // 通过布尔值 判断密码是否一致
              // let isLogin = aes.aesDecrypt(明文（用户提交的参数）, 加密的（数据表中的字段）)
              let isLogin = aes.aesDecrypt(password, user.密码);
              // console.log({isLogin})
              if (isLogin) {
                // 给前端提示
                resolve({
                  code: 200,
                  msg: `${account},登录成功`,
                });
              } else {
                // 提示
                resolve({
                  code: -1,
                  msg: `账号或密码错误`,
                });
              }
            }
          }
        },
        (err) => {
          reject({
            code: 500,
            msg: "后台发生错误",
            err,
          });
        }
      );
    });
  }

  // 轮播图
  carousel(account, img) {
    return new Promise((resolve, reject) => {
      db.query(`select 账号 from pre_user where 账号='${account}'`).then(
        (rows) => {
          if (rows.length == 0) {
            // 不存在
            resolve({
              code: -1,
              msg: "该账号不存在",
            });
          } else {
            // 存在
            db.query(
              `INSERT INTO carousel (轮番图, 账号) VALUES ('${img}', '${account}')`
            ).then(
              (content) => {
                resolve({
                  code: 200,
                  msg: `设置轮番图成功`,
                  status: content.fieldCount === 0 ? "正常" : "异常",
                });
              },
              (error) => {
                reject({
                  code: -1,
                  msg: "服务端发生错误",
                  error,
                });
              }
            );
          }
        },
        (err) => {
          reject({
            code: -1,
            msg: "服务端发生错误",
            err,
          });
        }
      );
    });
  }

  // 查询轮播图
  carousel_list() {
    return new Promise((resolve, reject) => {
      db.query(`select  * from carousel`).then(
        (row) => {
          resolve({
            code: 200,
            msg: "获取轮番图成功",
            result: row,
          });
        },
        (error) => {
          reject({
            code: -1,
            msg: "获取轮番图失败",
            error,
          });
        }
      );
    });
  }

  // 获取用户列表
  list(page_num, page_size) {
    return new Promise((resolve, reject) => {
      db.query("select count(*) as total from pre_user")
        .then(
          (data) => {
            // console.log({ data });
            return data;
          },
          (err) => {
            reject({
              code: -1,
              msg: "统计失败",
              err,
            });
          }
        )
        .then((data) => {
          let num = (parseInt(page_num) - 1) * parseInt(page_size); // 从哪个位置开始获取
          let size = parseInt(page_size); // 获取多少条记录
          db.query(`select * from pre_user limit ${num} , ${size}`).then(
            (rows) => {
              resolve({
                code: 200,
                msg: "获取用户列表成功",
                total: data[0] && data[0].total,
                result: [...rows], // 指定数量的用户列表
              });
            },
            (err) => {
              reject({
                code: -1,
                msg: "获取用户列表失败",
                err,
              });
            }
          );
        });
    });
  }

  // 设置用户头像
  img1(account, imgUrl) {
    return new Promise((resolve, reject) => {
      db.query(`select 账号 from pre_user where 账号='${account}'`).then(
        (rows) => {
          if (rows.length == 0) {
            // 不存在
            resolve({
              code: -1,
              msg: "该账号不存在",
            });
          } else {
            // 存在
            db.query(
              `update pre_user set 头像= '${imgUrl}' where 账号= '${account}'`
            ).then(
              (content) => {
                resolve({
                  code: 200,
                  msg: `设置用户头像成功`,
                  status: content.fieldCount === 0 ? "正常" : "异常",
                });
              },
              (error) => {
                reject({
                  code: -1,
                  msg: "服务端发生错误",
                  error,
                });
              }
            );
          }
        },
        (err) => {
          reject({
            code: -1,
            msg: "服务端发生错误",
            err,
          });
        }
      );
    });
  }

  // 修改昵称
  updatename(account, text) {
    return new Promise((resolve, reject) => {
      // 先查询
      db.query(`select 账号 from pre_user where 账号='${account}'`).then(
        (row) => {
          if (row.length == 0) {
            resolve({
              code: 404,
              msg: `此账号“${account}”不存在`,
            });
          } else {
            // 修改考试分类名称
            db.query(
              `update pre_user set 昵称= '${text}' where 账号= '${account}'`
            )
              .then((content) => {
                resolve({
                  code: 200,
                  msg: `修改成功`,
                  status: content.fieldCount === 0 ? "正常" : "异常",
                });
              })
              .catch((error) => {
                reject({
                  code: -1,
                  msg: `修改失败`,
                  error,
                });
              });
          }
        }
      );
    });
  }

  // 删除
  remove(account) {
    return new Promise((resolve, reject) => {
      db.query(`select 账号 from pre_user where 账号 = '${account}'`).then(
        (rows) => {
          if (rows.length == 0) {
            // 说明不存在这个账号了
            resolve({
              code: -1,
              msg: `该账号不存在`,
            });
          } else {
            db.query(`delete from pre_user where 账号 = '${account}'`).then(
              (content) => {
                resolve({
                  code: 200,
                  msg: `删除账号成功，${rows[0].account}`,
                  status: content.changedRows === 0 ? "正常" : "异常",
                });
              },
              (error) => {
                reject({
                  code: -1,
                  msg: "删除账号失败",
                  error,
                });
              }
            );
          }
        },
        (err) => {
          reject({
            code: -1,
            msg: "查询账号失败",
            err,
          });
        }
      );
    });
  }

  // 上传图片
  img(account, imgUrl) {
    return new Promise((resolve, reject) => {
      // 检查 pre_user 表中是否存在该账号
      db.query(`SELECT 账号 FROM pre_user WHERE 账号='${account}'`)
        .then((rows) => {
          // 确保账号存在
          if (rows.length === 0) {
            return reject({
              code: -1,
              msg: "该账号不存在，请先注册账号",
            });
          }
          return Promise.resolve();
        })
        .then(() => {
          return db.query(
            `SELECT photo FROM photos WHERE account='${account}'`
          );
        })
        .then((rows) => {
          let existingPhotos = "";
          if (rows.length > 0) {
            existingPhotos = rows[0].photo; // 读取现有的图片链接
          }

          // 合并新的图片链接
          const updatedPhotos = existingPhotos
            ? existingPhotos + "\n" + imgUrl
            : imgUrl;

          // 插入或更新照片记录
          if (rows.length > 0) {
            // 更新现有记录
            return db.query(
              `UPDATE photos SET photo='${updatedPhotos}' WHERE account='${account}'`
            );
          } else {
            // 插入新记录
            return db.query(
              `INSERT INTO photos(account, photo) VALUES ('${account}', '${updatedPhotos}')`
            );
          }
        })
        .then(() => {
          resolve({
            code: 200,
            msg: `操作成功`,
            status: "正常",
          });
        })
        .catch((error) => {
          console.error("发生错误:", error);
          reject({
            code: -1,
            msg: "服务端发生错误",
            error: error.message || error,
          });
        });
    });
  }

  // 查询图片
  photo_list() {
    return new Promise((resolve, reject) => {
      db.query(`select  *  from photos`).then(
        (row) => {
          resolve({
            code: 200,
            msg: "获取图片成功",
            result: row,
          });
        },
        (error) => {
          reject({
            code: -1,
            msg: "获取图片失败",
            error,
          });
        }
      );
    });
  }

  // 获取所有用户列表
  AllList() {
    return new Promise((resolve, reject) => {
      db.query(`select  *  from pre_user`).then(
        (row) => {
          resolve({
            code: 200,
            msg: "获取用户信息成功",
            result: row,
          });
        },
        (error) => {
          reject({
            code: -1,
            msg: "获取用户信息失败",
            error,
          });
        }
      );
    });
  }
}
module.exports = User;
